﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Security;
using System.Security.Permissions;
using System.Security.Policy;
using CodeGeneration.Model;
using CodeGeneration.TextEngine;
using CodeGeneration.Util;
using RazorEngine;
using RazorEngine.Configuration;
using RazorEngine.Templating;
using RazorEngine.Text;

namespace CodeGeneration
{
    class Program
    {
        static int Main(string[] args)
        {
            #region 如果是RazorEngine 需要通过这段代码清理缓存
            if (AppDomain.CurrentDomain.IsDefaultAppDomain())
            {
                // RazorEngine cannot clean up from the default appdomain...
                //Console.WriteLine("Switching to secound AppDomain, for RazorEngine...");
                AppDomainSetup adSetup = new AppDomainSetup
                {
                    ApplicationBase = AppDomain.CurrentDomain.SetupInformation.ApplicationBase
                };
                var current = AppDomain.CurrentDomain;
                // You only need to add strongnames when your appdomain is not a full trust environment.
                var strongNames = new StrongName[0];

                var domain = AppDomain.CreateDomain(
                    "MyMainDomain", null,
                    current.SetupInformation, new PermissionSet(PermissionState.Unrestricted),
                    strongNames);
                var exitCode = domain.ExecuteAssembly(Assembly.GetExecutingAssembly().Location);
                // RazorEngine will cleanup. 
                AppDomain.Unload(domain);
                return exitCode;
            }
            #endregion

            ITextEngine textEngine=new RazorTextEngine();
            //ITextEngine textEngine=new DotLiquidTextEngine();
            //ITextEngine textEngine = new NVelocityTextEngine();
            var generator = new Generator(textEngine);

            var tables = SqlUtil.GetDbTables(SqlUtil.ConnectionString, SqlUtil.DbDatabase, string.Join(",", SqlUtil.TableNames));
            foreach (var dbTable in tables)
            {
                var columns = SqlUtil.GetDbColumns(SqlUtil.ConnectionString, SqlUtil.DbDatabase, dbTable.TableName);
                var model = new EntityModel { ClassName = dbTable.TableName, NameSpace = "CustomFramework.Model", Properties = columns.Select(c => new EntityProperty { CSharpType = c.CSharpType, IsNullable = c.CommonType.IsValueType && c.IsNullable, IsPrimaryKey = c.IsPrimaryKey, Name = c.ColumnName, Remark = c.Remark }).ToList() };
                generator.Generate(model, $"Output/{model.ClassName}.generated.cs");

            }

            generator.Generate(new TestModel { ClassName = "bbcd" }, "Output/7.cs");

            return 0;
        }
    }
}
